package com.zoho.daliansheng.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zoho.daliansheng.common.U8SystemRecord;
import com.zoho.daliansheng.common.ZohoRecord;
import com.zoho.daliansheng.config.CRMPathConfig;
import com.zoho.daliansheng.config.DatasourceEnum;
import com.zoho.daliansheng.config.U8SystemPathConfig;
import com.zoho.daliansheng.dlcr.DlcrU8WebService;
import com.zoho.daliansheng.dlcr.DlcrU8WebServiceSoap;
import com.zoho.daliansheng.dlcr.QueryRetInfo;
import com.zoho.daliansheng.utils.CrmApiUtil;
import com.zoho.daliansheng.utils.getCrmFieldUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Service
public class WarehouseServiceImpl implements WarehouseService {

    ZohoRecord zohoRecord;

    U8SystemRecord u8SystemRecord;

    U8SystemPathConfig u8SystemPathConfig;

    CRMPathConfig crmPathConfig;

    public WarehouseServiceImpl(ZohoRecord zohoRecord, U8SystemRecord u8SystemRecord, U8SystemPathConfig u8SystemPathConfig, CRMPathConfig crmPathConfig) {
        this.zohoRecord = zohoRecord;
        this.u8SystemRecord = u8SystemRecord;
        this.u8SystemPathConfig = u8SystemPathConfig;
        this.crmPathConfig = crmPathConfig;
    }

    @Override
    public void synWarehouse() {
        /*
         * 1 获取CRM 产品仓库模块数据
         */
        List<String> fieldList = getCrmFieldUtil.getWarehouseFieldList();
        List<JSONObject> crmData = CrmApiUtil.getModuleData(zohoRecord.getAccessToken(), crmPathConfig.getWarehouseModuleName(), fieldList);
        /*
         * 2 同步ERP仓库数据
         */
        try {
//            synU8Data(crmData, DatasourceEnum.GONG_CHANG.getWebServiceUrl(), DatasourceEnum.GONG_CHANG.getCompanyName(), DatasourceEnum.GONG_CHANG.getAccountCode());
            synU8Data(crmData, DatasourceEnum.SU_ZHOU.getWebServiceUrl(), DatasourceEnum.SU_ZHOU.getCompanyName(), DatasourceEnum.SU_ZHOU.getAccountCode());
            synU8Data(crmData, DatasourceEnum.CHANG_ZHOU.getWebServiceUrl(), DatasourceEnum.CHANG_ZHOU.getCompanyName(), DatasourceEnum.CHANG_ZHOU.getAccountCode());
            synU8Data(crmData, DatasourceEnum.DA_LIAN.getWebServiceUrl(), DatasourceEnum.DA_LIAN.getCompanyName(), DatasourceEnum.DA_LIAN.getAccountCode());
            synU8Data(crmData, DatasourceEnum.XIN_CAI_LIAO.getWebServiceUrl(), DatasourceEnum.XIN_CAI_LIAO.getCompanyName(), DatasourceEnum.XIN_CAI_LIAO.getAccountCode());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void synU8Data(List<JSONObject> crmData, String webServiceUrl, String companyName, String accountCode) throws Exception {

        String synModuleName = crmPathConfig.getWarehouseModuleName(); // 要同步的模块名称

        // 1 过滤CRM数据，只保留单一账套
        crmData = crmData.stream().filter(object -> Objects.nonNull(object.getString("AffiliatedCompany")) && object.getString("AffiliatedCompany").equals(companyName)).collect(Collectors.toList());

        // 2 模块最大版本号
        Map<String, String> map = CrmApiUtil.getMaxVersion(zohoRecord.getAccessToken(), synModuleName, accountCode);
        String versionCrmId = map.get("id");
        int maxVersion = Integer.parseInt(map.get("maxVersion"));

        // 3 获取ERP数据
        DlcrU8WebService webService = new DlcrU8WebService(new URL(webServiceUrl));
        DlcrU8WebServiceSoap api = webService.getDlcrU8WebServiceSoap();
        QueryRetInfo queryRetInfo = api.queryWarehouseByVersion(maxVersion);
        int queryMaxVersion = queryRetInfo.getMaxVersion();
        JSONArray jsonArray = JSONArray.parseArray(queryRetInfo.getJson());
        if (jsonArray.size() > 0) {

            // 4 比较数据
            List<JSONObject> insertList = new ArrayList<>();
            List<JSONObject> updateList = new ArrayList<>();
            List<String> deleteList = new ArrayList<>();
            List<JSONObject> batchWarehouse = jsonArray.toJavaList(JSONObject.class);

            if (maxVersion == -1) {
                if(crmData.size() == 0){
                    insertList = batchWarehouse;
                }else{
                    for (JSONObject erpData : batchWarehouse) {
                        String code = erpData.getString("cwhcode"); // 仓库编码
                        List<JSONObject> searchList = crmData.stream().filter(object -> Objects.nonNull(object.getString("warehouse_code")) &&
                                object.getString("warehouse_code").equals(code)  &&  object.getString("AffiliatedCompany").equals(companyName)
                        ).collect(Collectors.toList());
                        if (searchList.size() > 0) {
                            JSONObject jsonObject = searchList.get(0);
                            String crmId = jsonObject.getString("id");
                            erpData.put("crmId", crmId);
                            updateList.add(erpData);
                        }else{
                            insertList.add(erpData);
                        }
                    }
                }

            } else {
                for (JSONObject erpData : batchWarehouse) {
                    // sys_change_operation 该字段非常关键,记录了记录的变动类型,I=Insert、U=Update、D=Delete
                    String operation = erpData.getString("sys_change_operation");

                    String code = erpData.getString("cwhcode"); // 仓库编码
                    List<JSONObject> searchList = crmData.stream().filter(object -> Objects.nonNull(object.getString("warehouse_code")) &&
                            object.getString("warehouse_code").equals(code)  &&  object.getString("AffiliatedCompany").equals(companyName)).collect(Collectors.toList());

                    if ("I".equals(operation)) {
                        insertList.add(erpData);
                    } else if ("U".equals(operation)) {
                        if (searchList.size() > 0) {
                            JSONObject jsonObject = searchList.get(0);
                            String crmId = jsonObject.getString("id");
                            erpData.put("crmId", crmId);
                            updateList.add(erpData);
                        }
                    } else if ("D".equals(operation)) {
                        log.info("仓库删除数据：{}", erpData.toJSONString());
                        log.info("仓库searchList：{}", JSONObject.toJSONString(searchList));
                        if (searchList.size() > 0) {
                            JSONObject jsonObject = searchList.get(0);
                            String crmId = jsonObject.getString("id");
                            deleteList.add(crmId);
                        }
                    }
                }
            }

            // 5 字段映射
            List<JSONObject> crm_insertList = getCrmMappingData(insertList, companyName);
            List<JSONObject> crm_updateList = getCrmMappingData(updateList, companyName);
            log.info("同步【" + companyName + "】");
            //System.out.println("JSONObject.toJSONString(batchWarehouse) = " + JSONObject.toJSONString(batchWarehouse));
            System.out.println("crm_insertList.size() = " + crm_insertList.size());
            System.out.println("crm_updateList.size() = " + crm_updateList.size());
            System.out.println("deleteList.size() = " + deleteList.size());

            // 6 批量操作
            CrmApiUtil.batchInsertDataByList(zohoRecord.getAccessToken(), crm_insertList, synModuleName);
            CrmApiUtil.batchUpdateDataByList(zohoRecord.getAccessToken(), crm_updateList, synModuleName);
            if(deleteList.size()>0){
                CrmApiUtil.batchDeleteModelData(zohoRecord.getAccessToken(), synModuleName, deleteList);
            }

            // 7 最大版本号回传
            if (queryMaxVersion != maxVersion) {
                CrmApiUtil.saveMaxVersion(zohoRecord.getAccessToken(), versionCrmId, queryMaxVersion, crmPathConfig.getMaxVersionModuleName());
            }
        }
    }


    private List<JSONObject> getCrmMappingData(List<JSONObject> erpList, String companyName) {
        List<JSONObject> list = new ArrayList<>();
        for (JSONObject erpData : erpList) {
            JSONObject crmData = new JSONObject();
            String crmId = erpData.getString("crmId");
            if (StringUtils.isNotBlank(crmId)) {
                crmData.put("id", crmId);
            }
            crmData.put("AffiliatedCompany", companyName); // 所属公司
            crmData.put("Name", erpData.getString("cwhname")); // 仓库名称
            crmData.put("warehouse_code", erpData.getString("cwhcode")); // 仓库编码
            crmData.put("warehouse_address", erpData.getString("cwhaddress")); // 仓库地址
            crmData.put("phone", erpData.getString("cwhphone")); // 电话
            String personName = erpData.getString("cwhperson");
            if (StringUtils.isNotBlank(personName)) {
                crmData.put("charge_person", personName); // 负责人
            } else {
                crmData.put("charge_person", erpData.getString("personcode")); // 负责人
            }
            list.add(crmData);
        }
        return list;
    }
}
